{% extends 'base.html' %}
{% block title %}编辑菜谱 - {{ recipe.title }}{% endblock %}

{% block content %}
    <div class="mx-auto" style="max-width: 700px;">
        <h2 class="mb-4">编辑菜谱</h2>

        <form method="post" enctype="multipart/form-data" novalidate>
            {% csrf_token %}
            {{ form.non_field_errors }}

            <div class="mb-3">
                {{ form.title.label_tag }}
                {{ form.title }}
                {% if form.title.errors %}
                    <div class="text-danger small">{{ form.title.errors }}</div>
                {% endif %}
            </div>

            <div class="mb-3">
                {{ form.description.label_tag }}
                {{ form.description }}
                {% if form.description.errors %}
                    <div class="text-danger small">{{ form.description.errors }}</div>
                {% endif %}
            </div>

            <div class="mb-3">
                {{ form.ingredients.label_tag }}
                {{ form.ingredients }}
                {% if form.ingredients.errors %}
                    <div class="text-danger small">{{ form.ingredients.errors }}</div>
                {% endif %}
            </div>

            <div class="mb-3">
                {{ form.steps.label_tag }}
                {{ form.steps }}
                {% if form.steps.errors %}
                    <div class="text-danger small">{{ form.steps.errors }}</div>
                {% endif %}
            </div>

            <div class="mb-3">
                {{ form.notes.label_tag }}
                {{ form.notes }}
                {% if form.notes.errors %}
                    <div class="text-danger small">{{ form.notes.errors }}</div>
                {% endif %}
            </div>
            <div class="mb-3">
                {{ form.difficulty.label_tag }}
                {{ form.difficulty }}
                {% if form.difficulty.errors %}
                    <div class="text-danger small">{{ form.difficulty.errors }}</div>
                {% endif %}
            </div>
            <div class="mb-3">
                {{ form.estimated_minutes.label_tag }}
                {{ form.estimated_minutes }}
                {% if form.estimated_minutes.errors %}
                    <div class="text-danger small">{{ form.estimated_minutes.errors }}</div>
                {% endif %}
            </div>

            <div class="mb-3">
                {{ form.price_tier.label_tag }}
                {{ form.price_tier }}
                {% if form.price_tier.errors %}
                    <div class="text-danger small">{{ form.price_tier.errors }}</div>
                {% endif %}
            </div>
            <div class="mb-3">
                {{ form.is_takeaway_available.label_tag }}
                {{ form.is_takeaway_available }}
                {% if form.is_takeaway_available.errors %}
                    <div class="text-danger small">{{ form.is_takeaway_available.errors }}</div>
                {% endif %}
            </div>
            <div class="mb-3">
                {{ form.health_index.label_tag }}
                {{ form.health_index }}
                {% if form.health_index.errors %}
                    <div class="text-danger small">{{ form.health_index.errors }}</div>
                {% endif %}
            </div>
            <div class="mb-3">
                {{ form.link.label_tag }}
                {{ form.link }}
                {% if form.link.errors %}
                    <div class="text-danger small">{{ form.link.errors }}</div>
                {% endif %}
            </div>

            <div class="mb-3">
                <label for="id_tags" class="form-label">标签</label>
                {{ form.tags }}
                <div class="form-text">
                    没有你要的标签？<a href="{% url 'manage_tags' %}">去添加标签</a>
                </div>
            </div>

            <!-- 新增分类选择 -->
            <div class="mb-3">
                <label for="id_category" class="form-label">美食分类</label>
                <select id="id_category" name="category" class="form-select" required>
                    <option value="" disabled {% if not recipe.category %}selected{% endif %}>请选择分类</option>
                    {% for cat in categories %}
                        <option value="{{ cat.id }}"
                                {% if recipe.category and recipe.category.id == cat.id %}selected{% endif %}>{{ cat.name }}</option>
                    {% endfor %}
                </select>

            </div>

            <!-- 新增评分输入 -->
            <div class="mb-3">
                <label for="id_rating" class="form-label">评分 (0-5)</label>
                <input type="number" step="0.1" min="0" max="5" id="id_rating" name="rating" class="form-control"
                       placeholder="例如4.5"
                       value="{{ recipe.rating|default_if_none:'' }}">
            </div>

            <!-- 位置输入，仅堂食时显示 -->
            <div class="mb-3 d-none" id="location_group">
                <label for="id_location" class="form-label">位置（仅堂食填写）</label>
                <input type="text" id="id_location" name="location" class="form-control" placeholder="请输入位置"
                       value="{{ recipe.location|default_if_none:'' }}">
            </div>

            <!-- 店铺名输入，仅外卖时显示 -->
            <div class="mb-3 d-none" id="shop_name_group">
                <label for="id_shop_name" class="form-label">店铺名字（仅外卖填写）</label>
                <input type="text" id="id_shop_name" name="shop_name" class="form-control" placeholder="请输入店铺名"
                       value="{{ recipe.shop_name|default_if_none:'' }}">
            </div>

            {% if recipe.images.all %}
                <div class="mb-4">
                    <label class="form-label fw-semibold">已上传图片</label>
                    <div class="row g-3">
                        {% for img in recipe.images.all %}
                            <div class="col-sm-6 col-md-4">
                                <div class="card h-100 shadow-sm">
                                    <img src="{{ img.image.url }}" class="card-img-top rounded-top" alt="图片"
                                         style="height: 150px; object-fit: cover;">
                                    <div class="card-body text-center p-2">
                                        <button type="button"
                                                class="btn btn-sm btn-outline-danger w-100"
                                                data-bs-toggle="modal"
                                                data-bs-target="#deleteImageModal"
                                                data-img-id="{{ img.id }}"
                                                data-img-url="{{ img.image.url }}">
                                            删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            {% endif %}

            <div class="mb-3">
                <label for="id_images" class="form-label">上传图片（可追加）</label>
                <input type="file" name="images" id="id_images" multiple class="form-control">
            </div>

            <div class="d-grid">
                <button class="btn btn-primary">💾 保存修改</button>
            </div>
        </form>
    </div>

    <!-- 删除图片的模态框 -->
    <div class="modal fade" id="deleteImageModal" tabindex="-1" aria-labelledby="deleteImageModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <form method="post" id="deleteImageForm">
                {% csrf_token %}
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteImageModalLabel">确认删除图片</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                    </div>
                    <div class="modal-body text-center">
                        <p>你确定要删除这张图片吗？</p>
                        <img id="modalPreviewImage" src="" alt="预览" class="img-fluid rounded"
                             style="max-height: 200px;">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-danger">确认删除</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- JS 脚本：绑定删除按钮与模态框 -->
    <script>
        const deleteImageModal = document.getElementById('deleteImageModal');
        deleteImageModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const imgId = button.getAttribute('data-img-id');
            const imgUrl = button.getAttribute('data-img-url');

            const previewImage = deleteImageModal.querySelector('#modalPreviewImage');
            previewImage.src = imgUrl;

            const form = deleteImageModal.querySelector('#deleteImageForm');
            form.action = "{% url 'delete_image' 0 %}".replace('0', imgId);
        });

        // 分类选择动态显示输入框
        function updateCategoryFields() {
            const select = document.getElementById('id_category');

            const category = select.options[select.selectedIndex].text;
            const locationGroup = document.getElementById('location_group');
            const shopNameGroup = document.getElementById('shop_name_group');

            if (category === '堂食') {
                locationGroup.classList.remove('d-none');
                shopNameGroup.classList.add('d-none');
            } else if (category === '外卖') {
                shopNameGroup.classList.remove('d-none');
                locationGroup.classList.add('d-none');
            } else {
                locationGroup.classList.add('d-none');
                shopNameGroup.classList.add('d-none');
            }
        }

        document.getElementById('id_category').addEventListener('change', updateCategoryFields);
        document.addEventListener('DOMContentLoaded', updateCategoryFields);
    </script>
{% endblock %}
